package com.bw.lib_storage.db

import android.content.Context
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import net.sqlcipher.database.SupportFactory

/**
 * @author gjm
 * @date 2025/9/15
 * @description
 */
object DBUtils {
    lateinit var db: AppDataBase

    /**
     * 初始化数据库
     */
    fun initDB(context: Context,dbName:String) {
        //版本升级1-2:新增时间字段
        val MIGATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE history ADD COLUMN query_time INTEGER NOT NULL DEFAULT 0")
            }
        }

        db = Room.databaseBuilder(
            context,
            AppDataBase::class.java,
            dbName
        ).allowMainThreadQueries()
            .openHelperFactory(SupportFactory("123456".toByteArray()))
            .build()
    }

    fun getDB(): AppDataBase {
        if (db == null){
            throw NullPointerException("请先初始化数据库")
        }
        return db
    }
}